//
//  MapViewController.m
//  gee
//
//  Created by gakaki on 11-5-19.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "UserLocationViewController.h"


@implementation UserLocationViewController


@synthesize locationManager;
@synthesize startingPoint;
@synthesize map_view;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
  
    
	map_view.mapType=MKMapTypeStandard;
	map_view.delegate=self;
   
    
    map_view.showsUserLocation = YES;
	map_view.zoomEnabled = YES;
    
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
   
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"地图服务"
                              message:@"地图服务尚未启用,请至 设置 -> 定位服务,开启 定位服务"
                              delegate:nil
                              cancelButtonTitle:@"确认"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    [locationManager startUpdatingLocation];
    
    NSLog(@"location manager is start");
    
    
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    locationManager = nil;
    startingPoint   = nil;
    map_view        = nil; 
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)dealloc
{
    [locationManager release];
    [startingPoint release];
    [map_view release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation {
	
	if (startingPoint == nil)
		self.startingPoint = newLocation;
	
	NSString *latitudeString = [[NSString alloc] initWithFormat:@"%g\u00B0",
								newLocation.coordinate.latitude];

    [latitudeString my_log:nil];
	[latitudeString release];
	
	NSString *longitudeString = [[NSString alloc] initWithFormat:@"%g\u00B0",
								 newLocation.coordinate.longitude];
	[longitudeString my_log:@"longitudeString coordinate 的 经度"];
	[longitudeString release];
	
	NSString *horizontalAccuracyString = [[NSString alloc]
										  initWithFormat:@"%gm",
										  newLocation.horizontalAccuracy];
	[horizontalAccuracyString my_log:@"horizontalAccuracyString   垂直检测精确度"];
	[horizontalAccuracyString release];
	
	NSString *altitudeString = [[NSString alloc] initWithFormat:@"			%gm",
								newLocation.altitude];
	[altitudeString my_log:@"altitudeString 海拔"];

	[altitudeString release];
	
	NSString *verticalAccuracyString = [[NSString alloc]
										initWithFormat:@"%gm",
										newLocation.verticalAccuracy];
	[verticalAccuracyString my_log:@"verticalAccuracyString 水平检测精确度"];
	[verticalAccuracyString release];
	
	CLLocationDistance distance = [newLocation
								   distanceFromLocation:startingPoint];
	NSString *distanceString = [[NSString alloc]
								initWithFormat:@"%gm", distance];
	[distanceString my_log:@"distanceString "];
    [distanceString release];
    
    // Keep track of the best location found
	if (!self.startingPoint) self.startingPoint = newLocation;
	else if (newLocation.horizontalAccuracy <  startingPoint.horizontalAccuracy) self.startingPoint = newLocation;
                         
    [map_view setRegion:MKCoordinateRegionMakeWithDistance(startingPoint.coordinate, 0.1f, 0.1f) animated:YES];
                                             
                                             
    
    
    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
	
    NSString *errorType = (error.code == kCLErrorDenied) ?
	@"Access Denied" : @"Unknown Error";
    UIAlertView *alert = [[UIAlertView alloc]
						  initWithTitle:@"尚未获取到坐标"
						  message:errorType
						  delegate:nil
						  cancelButtonTitle:@"Okay"
						  otherButtonTitles:nil];
    [alert show];
    [alert release];
}


#pragma mapview_delegate


- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
	MapUserAnn *annotation = view.annotation;
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://g.cn"]];
}

- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id <MKAnnotation>)annotation  
{  
    
    
    if(![annotation isKindOfClass:[MapUserAnn class]]) // Don't mess user location  
        return nil;  
    MKAnnotationView *annotationView = [aMapView dequeueReusableAnnotationViewWithIdentifier:@"spot"];  
    if(!annotationView)  
    {  
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"spot"];  
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];  
        [(UIButton *)annotationView.rightCalloutAccessoryView addTarget:self action:@selector(touchMapAnnotation:) forControlEvents:UIControlEventTouchUpInside];  
        annotationView.enabled = YES;  
        annotationView.canShowCallout = YES;  
        annotationView.centerOffset = CGPointMake(7,-15);  
        annotationView.calloutOffset = CGPointMake(-8,0);  
    }  
    // Setup annotation view  
    annotationView.image = [UIImage imageNamed:@"arrow.png"]; // Or whatever  
    return annotationView;  
}  

-(void)touchMapAnnotation{

    NSLog(@"touched");
}
// Update map when the user interacts with it
- (void)mapView:(MKMapView *)aMapView regionDidChangeAnimated:(BOOL)animated
{
	// Gather annotations
	MapUserAnn *annotation;
	NSMutableArray *annotations = [NSMutableArray array];
	self.title = @"Searching...";
	
	// Add a current location annotation
	if (self.startingPoint)
	{
		annotation = [[[MapUserAnn alloc] initWithCoordinate:self.startingPoint.coordinate] autorelease];
		annotation.title = @"当前所在点";
		[annotations addObject:annotation];
	}
	
	// Clean up the map
	[map_view removeAnnotations:map_view.annotations];
	
	// fetch all the new locations from outside.in, while showing the network indicator
	// delayed selector allows title to update in a timely manner during the network operation
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	//[self performSelector:@selector(setTitle:) withObject:@"Contacting Outside.in..." afterDelay:0.1f];
    
     
    
    // Add an annotation for each "place", using the coordinates, name and URL
    
     
        [ASIHTTPRequest setDefaultUserAgentString:@"GEE IPHONE IOS4 1.0"];
        [ASIHTTPRequest setDefaultTimeOutSeconds:2];
        
        NSURL *url = [NSURL URLWithString:@"http://192.168.2.118/geo.php"];
        
        
        __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request setPostValue:@"31" forKey:@"lat"];
        [request setPostValue:@"121"  forKey:@"long"];
        
        [request setCompletionBlock:^{
            // Use when fetching text data
            NSString *responseString = [request responseString];
            
            // Use when fetching binary data
            //NSData *responseData = [request responseData];
            
            //NSLog(@"%@",responseData);
            //NSLog(@"%@",responseString);
            
            
            NSArray *locs = [responseString objectFromJSONString];
            //        NSLog(@"%@",locs);
            //        NSLog(@"%@",[locs lastObject]); 
            //        NSLog(@"%d",[locs count]);
            //        NSLog(@"%@",[locs objectAtIndex:0]);
            //        
            for(NSDictionary *dict in locs) {
                NSLog(@"%@",[dict objectForKey:@"address"]);
                NSLog(@"%@",[dict objectForKey:@"description"]);
                NSLog(@"%@",[dict objectForKey:@"uuid"]);
                NSLog(@"%@",[dict objectForKey:@"uid"]);
                NSLog(@"%@",[dict objectForKey:@"time"]);
                NSLog(@"%@",[dict objectForKey:@"yyyy"]);
                NSArray *lloc = [dict objectForKey:@"loc"];
                NSLog(@"%@",[lloc objectAtIndex:0]);
                NSLog(@"%@",[lloc objectAtIndex:1]);
                
                
                
                
                CLLocationCoordinate2D coord;
                coord.latitude =  [[lloc objectAtIndex:0] floatValue];
                coord.longitude = [[lloc objectAtIndex:1] floatValue];
                
                // Create the annotation
                MapUserAnn *annotation = [[[MapUserAnn alloc] initWithCoordinate:coord] autorelease];
                annotation.title    = [dict objectForKey:@"address"];
                annotation.subtitle = [dict objectForKey:@"description"];
                
                // Add it
                [annotations addObject:annotation];
                
            }
            
            
            // Stop showing the network indicator and add the annotations
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            [map_view addAnnotations:annotations];

        }];
        [request setFailedBlock:^{
            NSError *error = [request error];
            NSLog(@"error data %@",error); 
        }];
        
        
        [request startAsynchronous];
     
    

}

@end
